<template>
    <div class="tools-location-page _page">
        <div class="map-container" ref="mapContainerEl"></div>
        <div class="info">
            <div>{{ currLocation.lng ? '经度：' + currLocation.lng : '' }}</div>
            <div>{{ currLocation.lat ? '纬度：' + currLocation.lat : '' }}</div>
            <div v-show="currLocation.address">{{ currLocation.address }}</div>
        </div>
        <div class="self-def-pos">
            <input type="number" @blur="doBlurSelfDefPos" placeholder="纬度" v-model.trim="selfDefPos.lat"/>
            <input type="number" @blur="doBlurSelfDefPos" placeholder="经度" v-model.trim="selfDefPos.lng"/>
        </div>
    </div>
</template>

<script>
import { reactive, ref, onMounted, onBeforeUnmount } from 'vue'
import { init, getCurrLocation, createMarker, getPlaceByLatlng } from './util'
import { useToastStore } from '@/stores/toast'
import { useRouter, useRoute } from 'vue-router'
import { addLeaflet } from '@/lib/util'

export default {
    setup () {
        const router = useRouter()
        const route = useRoute()
        const toast = useToastStore()
        const mapContainerEl = ref(null)
        let mapInstance = null
        let locationMarker = null
        let blurEventTime = 0
        const currLocation = reactive({
            lat: '',
            lng: '',
            address: ''
        })
        const selfDefPos = reactive({
            lat: '',
            lng: ''
        })

        const updateData = async (lat, lng) => {
            currLocation.lat = lat
            currLocation.lng = lng
            currLocation.address = await getPlaceByLatlng(lat, lng)
            selfDefPos.lat = lat + ''
            selfDefPos.lng = lng + ''
            router.replace({ name: 'tools-currLocation', query: { lat, lng } })
        }

        const enableMarkerDrag = () => {
            locationMarker.on('drag', e => {
                currLocation.lat = e.latlng.lat
                currLocation.lng = e.latlng.lng
                currLocation.address = ''
            })
            locationMarker.on('dragend', async (e) => {
                const obj = e.target._latlng
                updateData(obj.lat, obj.lng)
            })
        }

        const doBlurSelfDefPos = () => {
            blurEventTime = Date.now()
            if (selfDefPos.lat && selfDefPos.lng && !isNaN(selfDefPos.lat) && !isNaN(selfDefPos.lng)) {
                const arr = [selfDefPos.lat - 0, selfDefPos.lng - 0]
                updateData(...arr)
                if (!locationMarker) {
                    locationMarker = createMarker(mapInstance, arr)
                    enableMarkerDrag()
                } else {
                    locationMarker.setLatLng(arr)
                }
                mapInstance.setView(arr, 17)
            }
        }

        onMounted(async () => {
            await addLeaflet()
            mapInstance = init(mapContainerEl.value)
            mapInstance.on('click', e => {
                if (Date.now() - blurEventTime > 2000) {
                    const latlng = e.latlng
                    updateData(latlng.lat, latlng.lng)
                    if (!locationMarker) {
                        locationMarker = createMarker(mapInstance, [latlng.lat, latlng.lng])
                        enableMarkerDrag()
                    } else {
                        locationMarker.setLatLng([latlng.lat, latlng.lng])
                    }
                }
            })
            const query = route.query
            if (query && query.lat && query.lng && !isNaN(query.lat) && !isNaN(query.lng)) {
                const initLatLng = [query.lat - 0, query.lng - 0]
                mapInstance.setView(initLatLng, 17)
                locationMarker = createMarker(mapInstance, initLatLng)
                enableMarkerDrag()
                updateData(...initLatLng)
            } else {
                const locRes = await getCurrLocation()
                if (locRes.status) {
                    const latlng = locRes.latlng
                    mapInstance.setView(latlng, 17)
                    locationMarker = createMarker(mapInstance, latlng)
                    enableMarkerDrag()
                    updateData(...latlng)
                } else {
                    toast.warning(locRes.msg)
                }
            }
        })

        onBeforeUnmount(() => {
            mapInstance.remove()
        })

        return {
            mapContainerEl,
            currLocation,
            selfDefPos,
            doBlurSelfDefPos
        }
    }
}
</script>

<style lang="scss">
    @use './style.scss';
</style>
